<template>
    <div>
      <table>
        <thead>
          <tr>
            <!-- 动态生成表头 -->
            <th v-for="column in displayColumns" :key="column">{{ column }}</th>
          </tr>
        </thead>
        <tbody>
          <!-- 循环渲染表格行 -->
          <tr v-for="(row, rowIndex) in paginatedData" :key="rowIndex">
            <td v-for="(value, colIndex) in row" :key="colIndex">{{ value }}</td>
            <!-- <td>
              <button @click="handleDelete(row[0])" class="delete-button">删除</button>
              <button @click="editRow(rowIndex)" class="modify-button">修改</button>
            </td> -->
          </tr>
        </tbody>
      </table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredInvoiceData.length">
        </el-pagination>
        <input type="text" id="analyzeSearch" v-model="analyzeQuery" placeholder="输入分析查询内容" class="analyze_search-input" />
        <button @click="handleAnalysis" :disabled="isAnalyzing" class="analysis-button">
          {{ isAnalyzing? '分析中...' : '分析数据' }}
        </button>
      </div>
      <div class="analysis-result-container">
        <textarea v-model="analysisResult" readonly class="analysis-result-textarea"></textarea>
      </div>
      <div id="totalPriceChart" style="width: 100%; height: 400px;"></div>
      <div id="invoiceNumberChart" style="width: 100%; height: 400px;"></div>
      <div id="taxRateChart" style="width: 100%; height: 400px;"></div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import * as echarts from 'echarts';
  
  export default {
    data() {
      return {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        invoiceData: [],
        displayColumns: ['No', '开票日期', '货物或应税劳务、服务名称', '单价', '数量', '税率'],
        searchQuery: '', // 查询条件
        filteredInvoiceData: [], // 过滤后的数据
        paginatedData: [], // 分页后的数据
        analysisResult: '', // 用于存储后端传来的数据分析结果
        isAnalyzing: false, // 加载状态
        analyzeQuery: '' // 用于存储分析输入框中的内容
      };
    },
    mounted() {
      this.fetchInvoiceData();
    },
    methods: {
      fetchInvoiceData() {
        // 发送 HTTP 请求获取 invoice 表数据
        axios.get('http://127.0.0.1:5000/api/invoice_data')
         .then(response => {
            this.invoiceData = response.data;
            this.filterData(); // 初始加载时也进行过滤
          })
         .catch(error => {
            console.error('获取数据出错:', error);
          });
      },
      filterData() {
        // 根据查询条件过滤数据
        if (!this.searchQuery) {
          this.filteredInvoiceData = this.invoiceData; // 如果没有查询条件，显示全部数据
        } else {
          const query = this.searchQuery.toLowerCase();
          this.filteredInvoiceData = this.invoiceData.filter(row => {
            // 检查每一行的每个字段是否包含查询内容
            return row.some(value => {
              return String(value).toLowerCase().includes(query);
            });
          });
        }
        this.paginateData(); // 过滤后重新分页
      },
      handleDelete(no) {
        const shouldDelete = window.confirm('您是否要删除？');
        if (shouldDelete) {
          this.deleteRow(no);
        }
      },
      deleteRow(no) {
        console.log("要发送的 No 值:", no);  // 添加这行日志
        // 向后端发送删除请求
        axios.post('http://127.0.0.1:5000/api/delete_data', { no })
         .then(response => {
            if (response.data.success) {
              // 如果删除成功，重新获取数据
              this.fetchInvoiceData();
            } else {
              console.error('删除失败:', response.data.message);
            }
          })
         .catch(error => {
            console.error('删除请求出错:', error);
          });
      },
      editRow(index) {
        // 这里应实现与后端交互以进行修改操作
        // 示例：仅在控制台输出要修改的行索引
        console.log('修改第', index, '行');
      },
      handleSizeChange(newSize) {
        this.pageSize = newSize;
        this.paginateData(); // 改变每页数量时重新分页
      },
      handleCurrentChange(newPage) {
        this.currentPage = newPage;
        this.paginateData(); // 改变页码时重新分页
      },
      paginateData() {
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        this.paginatedData = this.filteredInvoiceData.slice(startIndex, endIndex);
      },
      handleAnalysis() {
        this.isAnalyzing = true;
        this.analysisResult = '';
        // 将 searchQuery 作为参数发送给后端
        axios.post('http://127.0.0.1:5000/api/analyze_data', { searchQuery: this.searchQuery })
         .then(response => {
            if (response.data && response.data.result) {
              this.analysisResult = response.data.result;
            } else {
              this.analysisResult = '未获取到有效的分析结果';
            }
          })
         .catch(error => {
            console.error('分析数据出错:', error);
            this.analysisResult = `分析数据出错: ${error.message}`;
          })
         .finally(() => {
            this.isAnalyzing = false;
          });
      },
      showTotalPriceChart() {
        const goodsTotalPrice = {};
        this.invoiceData.forEach(row => {
          const goodsName = row[2];
          const price = parseFloat(row[3]);
          const quantity = parseFloat(row[4]);
          if (!isNaN(price) &&!isNaN(quantity)) {
            const totalPrice = price * quantity;
            if (goodsTotalPrice[goodsName]) {
              goodsTotalPrice[goodsName] += totalPrice;
            } else {
              goodsTotalPrice[goodsName] = totalPrice;
            }
          }
        });
  
        const goodsNames = Object.keys(goodsTotalPrice);
        const totalPrices = Object.values(goodsTotalPrice);
  
        const chartDom = document.getElementById('totalPriceChart');
        const myChart = echarts.init(chartDom);
        const option = {
          title: {
            text: '每种货物的总金额'
          },
          xAxis: {
            type: 'category',
            data: goodsNames,
            name: '货物名称'
          },
          yAxis: {
            type: 'value',
            name: '总金额'
          },
          series: [{
            data: totalPrices,
            type: 'bar',
            itemStyle: {
              color: '#62dec9'
            }
          }]
        };
  
        option && myChart.setOption(option);
      },
      showInvoiceNumberChart() {
        const invoiceCountByDate = {};
        this.invoiceData.forEach(row => {
          const invoiceDate = row[1];
          if (invoiceCountByDate[invoiceDate]) {
            invoiceCountByDate[invoiceDate]++;
          } else {
            invoiceCountByDate[invoiceDate] = 1;
          }
        });
  
        const invoiceDates = Object.keys(invoiceCountByDate);
        const invoiceCounts = Object.values(invoiceCountByDate);
  
        const chartDom = document.getElementById('invoiceNumberChart');
        const myChart = echarts.init(chartDom);
        const option = {
          title: {
            text: '按开票日期的发票录入数量'
          },
          xAxis: {
            type: 'category',
            data: invoiceDates,
            // axisLabel: {
            //     rotate: 45, // 横坐标标签旋转 45 度，避免标签重叠
            //     interval: 0 // 强制显示所有标签
            // },
            name: '开票日期'
          },
          yAxis: {
            type: 'value',
            name: '发票数量'
          },
          series: [{
            data: invoiceCounts,
            type: 'bar',
            itemStyle: {
              color: '#3db0d9'
            }
          }]
        };
  
        option && myChart.setOption(option);
      },
      showTaxRateChart() {
        const taxRateData = [];
        this.invoiceData.forEach(row => {
          const taxRateStr = row[5].trim();
          if (taxRateStr === '') {
            taxRateData.push(0);
            return;
          }
          let taxRate;
          if (taxRateStr.includes('%')) {
            taxRate = parseFloat(taxRateStr.replace('%', ''));
          } else {
            taxRate = parseFloat(taxRateStr);
          }
          if (isNaN(taxRate)) {
            taxRateData.push(0);
          } else {
            taxRateData.push(taxRate);
          }
        });
  
        const maxTaxRate = Math.max(...taxRateData);
        const minTaxRate = Math.min(...taxRateData);
        const step = (maxTaxRate - minTaxRate) / 10;
  
        const taxRateBuckets = [];
        for (let i = minTaxRate; i <= maxTaxRate; i += step) {
          taxRateBuckets.push({
            start: i,
            end: i + step,
            count: 0
          });
        }
  
        taxRateData.forEach(taxRate => {
          taxRateBuckets.forEach(bucket => {
            if (taxRate >= bucket.start && taxRate < bucket.end) {
              bucket.count++;
            }
          });
        });
  
        const bucketLabels = taxRateBuckets.map(bucket => `${bucket.start.toFixed(2)}% - ${(bucket.end).toFixed(2)}%`);
        const bucketCounts = taxRateBuckets.map(bucket => bucket.count);
  
        const chartDom = document.getElementById('taxRateChart');
        const myChart = echarts.init(chartDom);
        const option = {
          title: {
            text: '税率分布情况'
          },
          xAxis: {
            type: 'category',
            data: bucketLabels,
            name: '税率区间'
          },
          yAxis: {
            type: 'value',
            name: '发票数量'
          },
          series: [{
            data: bucketCounts,
            type: 'bar',
            itemStyle: {
              color: '#105fa0'
            }
          }]
        };
  
        option && myChart.setOption(option);
      }
    }
  };
  </script>
  
  <style scoped>
  table {
    width: 100%;
    border-collapse: collapse;
  }
  
  th,
  td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
  }
  
  th {
    background-color: #f2f2f2;
  }
  
  .totalPrice-button {
    background-color: #62dec9;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
  }
  
  .invoiceNumber-button {
    background-color: #3db0d9;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
  }
  
  .taxRate-button {
    background-color: #105fa0;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
  }
  
  .delete-button {
    background-color: #e9120a;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
  }
  
  .modify-button {
    background-color: #4273b3;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
  }
  
  .analysis-button {
    background-color: #6ab78d;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
  }
  
  .search-input {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-right: 10px;
    font-size: 14px;
    width: 300px; /* 可以根据需要调整宽度 */
  }
  
  .analyze_search-input {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-right: 0px;
    font-size: 14px;
    width: 500px; /* 可以根据需要调整宽度 */
  }
  
  .search-button {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
  }
  
  .pagination-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
  }
  
  .analysis-result-container {
    margin-top: 20px;
  }
  
  .analysis-result-textarea {
    width: 99%; /* 调整宽度为80% */
    height: 200px; /* 调整高度为200px */
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    resize: none;
  }
  </style>